package com.kingtsoft.study.webserivce.imp;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.kingtsoft.study.common.ContextHolder;
import com.kingtsoft.study.constant.Describable;
import com.kingtsoft.study.constant.DescribableEnum;
import com.kingtsoft.study.constant.ParamConstants;
import com.kingtsoft.study.exception.BusinessException;
import com.kingtsoft.study.model.StudyHomework;
import com.kingtsoft.study.model.StudyHomeworkDetail;
import com.kingtsoft.study.service.StudyHomeworkDetailService;
import com.kingtsoft.study.service.StudyHomeworkService;
import com.kingtsoft.study.util.FileUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.kingtsoft.study.webserivce.WebStudyHomeworkDetailService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Title:
 * Description:
 * Copyright: Copyright (c) 2017-03-30 下午3:01
 * Company: wondersgroup.com
 *
 * @author jerry.pan(潘健雷)
 * @version 1.0
 */
@Service
public class WebStudyHomeworkDetailServiceImpl implements WebStudyHomeworkDetailService {

    @Reference
    private StudyHomeworkDetailService studyHomeworkDetailService;

    @Reference
    private StudyHomeworkService studyHomeworkService;


    @Override
    public ModelAndView pageAddInit(ModelAndView mav, StudyHomeworkDetail homeworkDetail) {
        mav.addObject(ParamConstants.PAGE_TYPE_NAME, ParamConstants.PAGE_TYPE_ADD);
        String homeworkId = homeworkDetail.getHomeworkId();
        if (StringUtils.isNotBlank(homeworkId)) {
            StudyHomework homework = studyHomeworkService.load(homeworkId);
            mav.addObject("homework", homework);
        }
        mav.addObject("homeworkDetail", homeworkDetail);
        return mav;
    }

    @Override
    public ModelAndView pageEditInit(ModelAndView mav, StudyHomeworkDetail homeworkDetail) {
        mav.addObject(ParamConstants.PAGE_TYPE_NAME, ParamConstants.PAGE_TYPE_EDIT);
        String id = homeworkDetail.getId();
        String homeworkId = homeworkDetail.getHomeworkId();
        StudyHomework homework = null;
        if (StringUtils.isNotBlank(id)) {
            homeworkDetail = this.load(homeworkDetail.getId());
            homework = studyHomeworkService.load(homeworkDetail.getHomeworkId());
        } else if (StringUtils.isNotBlank(homeworkId)) {
            if (StringUtils.isNotBlank(homeworkId)) {
                homework = studyHomeworkService.load(homeworkId);
            }
            if (ContextHolder.getSessionStudent() == null) {
                throw new BusinessException(DescribableEnum.USER_IS_NOT_STUDENT);
            }
            String studentId = ContextHolder.getSessionStudent().getId();
            if (StringUtils.isBlank(studentId)) {
                throw new BusinessException(DescribableEnum.USER_IS_NOT_STUDENT);
            }
            StudyHomeworkDetail homeworkDetailNew = this.loadByHomeworkIdAndStudentId(homeworkId, studentId);
            if (homeworkDetailNew != null) {
                homeworkDetail = homeworkDetailNew;
            }
        }
//        String path = homeworkDetail.getPath();
//        if (StringUtils.isNotBlank(path)) {
//            try {
//                String url = FileUtil.getFileUrl(path);
//                homeworkDetail.setUrl(url);
//            } catch (IOException e) {
//            }
//        }
        mav.addObject("homeworkDetail", homeworkDetail);
        mav.addObject("homework", homework);
        return mav;
    }


    @Override
    public ModelAndView pageViewInit(ModelAndView mav, StudyHomeworkDetail homeworkDetail) {
        mav.addObject(ParamConstants.PAGE_TYPE_NAME, ParamConstants.PAGE_TYPE_VIEW);
        String id = homeworkDetail.getId();
        if (StringUtils.isNotBlank(id)) {
            homeworkDetail = studyHomeworkDetailService.load(homeworkDetail.getId());
            if (homeworkDetail != null) {
//                try {
//                    String path = homeworkDetail.getPath();
//                    if (StringUtils.isNotBlank(path)) {
//                        String url = FileUtil.getFileUrl(path);
//                        homeworkDetail.setUrl(url);
//                    }
//                } catch (IOException e) {
//                }
                String homeworkId = homeworkDetail.getHomeworkId();
                if (StringUtils.isNotBlank(homeworkId)) {
                    StudyHomework homework = studyHomeworkService.load(homeworkId);
                    mav.addObject("homework", homework);
                }
            }
        }
        mav.addObject("homeworkDetail", homeworkDetail);
        return mav;
    }


    /**
     * 获取作业
     *
     * @param id 作业主键
     * @return 作业
     * @author jerry.pan
     * @date 2017-03-30 15:08:11
     */
    @Override
    public StudyHomeworkDetail load(String id) {
        return studyHomeworkDetailService.load(id);
    }

    /**
     * 通过老师作业表主键和学生主键获取作业
     *
     * @param homeworkId 老师作业表主键
     * @return 作业
     * @author jerry.pan
     * @date 2017-04-01 12:39:56
     */
    @Override
    public StudyHomeworkDetail loadByHomeworkIdAndStudentId(String homeworkId, String studentId) {
        return studyHomeworkDetailService.loadByHomeworkIdAndStudentId(homeworkId, studentId);
    }

    /**
     * 分页获取作业的列表
     *
     * @return pageInfo
     * @author jerry.pan
     * @date 2017-03-30 15:08:11
     */
    @Override
    public PageInfo<StudyHomeworkDetail> listPage(PageInfo page, StudyHomeworkDetail studyHomeworkDetail) {
        return studyHomeworkDetailService.listPage(page, studyHomeworkDetail);
    }

    /**
     * 获取作业的列表
     *
     * @return list
     * @author jerry.pan
     * @date 2017-03-30 15:08:11
     */
    @Override
    public List<StudyHomeworkDetail> listAll(StudyHomeworkDetail studyHomework) {
        return studyHomeworkDetailService.listAll(studyHomework);
    }

    /**
     * 增加/修改作业
     *
     * @param studyHomeworkDetail 作业
     * @author jerry.pan
     * @date 2017-03-31 16:11:29
     */
    @Override
    public StudyHomeworkDetail edit(StudyHomeworkDetail studyHomeworkDetail) {
        String id = studyHomeworkDetail.getId();
        if (StringUtils.isBlank(id)) {//新增
            studyHomeworkDetail.setUserId(ContextHolder.getSessionUser().getId());
            if (ContextHolder.getSessionStudent() == null) {
                throw new BusinessException(DescribableEnum.USER_IS_NOT_STUDENT);
            }
            String studentId = ContextHolder.getSessionStudent().getId();
            if (StringUtils.isBlank(studentId)) {
                throw new BusinessException(DescribableEnum.USER_IS_NOT_STUDENT);
            }
            studyHomeworkDetail.setStudentId(studentId);
            studyHomeworkDetail.setCreateDate(new Date());
            studyHomeworkDetail.setUpdateDate(new Date());
            studyHomeworkDetail = studyHomeworkDetailService.add(studyHomeworkDetail);
        } else {
            studyHomeworkDetail.setUpdateDate(new Date());
            studyHomeworkDetail = studyHomeworkDetailService.edit(studyHomeworkDetail);
        }
        return studyHomeworkDetail;
    }

    /**
     * 保存上传文件
     *
     * @param file
     * @author jerry.pan
     * @date 2017-04-01 15:38:22
     */
    public StudyHomeworkDetail saveUpload(MultipartFile file, StudyHomeworkDetail studyHomeworkDetail) {
        String filename = file.getOriginalFilename();
        String suffix = FileUtil.getFileSuffix(filename);
        String relativePath;
        //保存到文件夹
        try {
            relativePath = FileUtil.upload(file);
            //改为通过id下载的方式
//            String url = FileUtil.getFileUrl(relativePath);//获取下载路径
//            studyHomeworkDetail.setUrl(url);
        } catch (IOException e) {
            throw new BusinessException(DescribableEnum.FILE_UPLOAD_ERROR);
        }
        studyHomeworkDetail.setFilename(filename);
        studyHomeworkDetail.setFileSize(BigDecimal.valueOf(file.getSize()));
        studyHomeworkDetail.setSuffix(suffix);
        studyHomeworkDetail.setPath(relativePath);
        studyHomeworkDetail = studyHomeworkDetailService.saveUpload(studyHomeworkDetail);
        return studyHomeworkDetail;
    }

    /**
     * 下载文件
     * @param response
     * @param id 学生作业表主键
     * @author jerry.pan
     */
    public void downloadFile(HttpServletResponse response, String id){
        StudyHomeworkDetail homeworkDetail = this.load(id);
        if (homeworkDetail == null) {
            throw new BusinessException(DescribableEnum.FILE_NOT_EXIST);
        }
        String filename = homeworkDetail.getFilename();
        String filePath = FileUtil.getPath(homeworkDetail.getPath());
        File file = new File(filePath);
        if (!file.exists()) {
            throw new BusinessException(DescribableEnum.FILE_NOT_EXIST);
        }
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            OutputStream out = response.getOutputStream();
            FileUtils.copyFile(file, out);
        } catch (IOException e) {
            throw new BusinessException(DescribableEnum.FILE_DOWNLOAD_ERROR);
        }
    }

    /**
     * 删除上传文件
     *
     * @param
     * @author jerry.pan
     * @date 2017-04-01 15:38:22
     */
    public void deleteFile(String id) {
        Map resultMap = studyHomeworkDetailService.deleteFile(id);
        Describable describable = (Describable)MapUtils.getObject(resultMap,"describable");
        if(!DescribableEnum.SUCCESS.equals(describable)){
            throw new BusinessException(describable);
        }
    }

    /**
     * 查询已经提交的作业
     *
     * @param page
     * @param studyHomeworkDetail
     * @return page info
     * @author jerry.pan
     * @date 2017-04-05 08:40:11
     */
    public PageInfo<StudyHomeworkDetail> listCommittedPage(PageInfo page, StudyHomeworkDetail studyHomeworkDetail) {
        return studyHomeworkDetailService.listCommittedPage(page, studyHomeworkDetail);
    }
}
